package mine.activity;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;


import com.android.volley.VolleyError;
import com.xkh.xkh.MyApplication;
import com.xkh.xkh.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import adcp.activities.AdcpActivity;
import bbs.activity.BbsMainActivity;
import chat.activities.IMActivity;
import chat.network.tcp.PushService;
import diaodu.activity.DiaoDuShowActivity;
import gatecontrol.activities.GateActivityControl;
import gis.activities.MapShow;
import gis.activities.MapShow2;
import gis.activities.MapShowActivity;
import gongqing.activities.GongqingActivity;
import inter.Delegate;
import managers.DatabaseManager;
import managers.UIHandler;
import managers.UserInfo;
import mine.network.GetVersion;
import shuiyuqing.activities.WaterActivity;
import utils.PackageUtil;
import weibo.acitivity.BokeActivity;
import weibo.acitivity.BokeActivity2;

/**
 * 功能界面
 * Created by 凯 on 2015/10/26.
 */
public class FunctionActivity extends UIHandler.BaseActivity {

    // 工情
    View v_gongqing;

    // 闸门控制
    View v_control;

    // 水雨情
    View v_water;

    // 配水
    View v_peishui;

    // adcp录入
    View v_adcp;

    // gis
    View v_gis;

    // 首页
    View v_main;

    // Chat
    View v_chat;

    // bbs
    View v_bbs;

    // 我的
    View v_my;

    ProgressDialog progressDialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_function);
        initview();
        // 若用户已经登录，却处于主动退出的状况
        showDialog2();
        checkversion();
    }

    private void checkversion() {
        GetVersion getVersion = new GetVersion();
        getVersion.setDelegate(new Delegate() {
            @Override
            public void onResponse(String response) {
                double newversion = Double.parseDouble(response);
                String versionname = PackageUtil.getVersionName(FunctionActivity.this);
                Double version = Double.parseDouble(versionname);
                if (version < newversion) {
                    showUpdateDialog();
                }

            }

            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        getVersion.get();
    }

    //显示是否要更新的对话框
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(android.R.drawable.ic_dialog_info);
        builder.setTitle("发现新版本");
        builder.setMessage("升级至新版app");
        builder.setCancelable(false);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                upgrade();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }

    // 升级app
    private void upgrade() {
        progressDialog = new ProgressDialog(FunctionActivity.this);    //进度条，在下载的时候实时更新进度，提高用户友好度
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setTitle("正在下载");
        progressDialog.setMessage("请稍候...");
        progressDialog.setMax(100);
        progressDialog.setProgress(0);
        progressDialog.setCancelable(false);
        progressDialog.show();

        UpgradThread up = new UpgradThread();
        up.setPath("http://"+getResources().getString(R.string.IP)+"/update/GetApp");
        up.start();

    }

    // 检查是否是被强制退出
    public void showDialog2() {
        if (MyApplication.isExitMust) {
            new AlertDialog.Builder(FunctionActivity.this).setTitle("重要消息")
                    .setMessage("此账号已在其他地方登陆").setPositiveButton("退出", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    // 删除数据库
                    DatabaseManager.getInstance().delete();
                    // 退出所有界面
                    UIHandler.uiHandler.finishiall();
                }
            }).setNegativeButton("强制登陆", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent intent = new Intent(FunctionActivity.this, PushService.class);
                    intent.putExtra(PushService.SERVICE_ACTION, PushService.ACTION_CONNECTION);
                    FunctionActivity.this.startService(intent);
                }
            }).setCancelable(false).show();
        }
    }

    View.OnClickListener itemClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (v == v_gongqing) {
                Intent intent = new Intent(FunctionActivity.this, DiaoDuShowActivity.class);
                startActivity(intent);
            } else if (v == v_control) {
                Intent intent = new Intent(FunctionActivity.this, GateActivityControl.class);
                startActivity(intent);
            } else if (v == v_water) {
                Intent intent = new Intent(FunctionActivity.this, WaterActivity.class);
                startActivity(intent);
            } else if (v == v_adcp) {
                Intent intent = new Intent(FunctionActivity.this, AdcpActivity.class);
                startActivity(intent);
            } else if (v == v_gis) {
                showDialog();
                Intent intent = new Intent(FunctionActivity.this, MapShowActivity.class);
                startActivity(intent);
            } else if (v == v_chat) {
                Intent intent = new Intent(FunctionActivity.this, IMActivity.class);
                startActivity(intent);
            } else if (v == v_bbs) {
                Intent intent = new Intent(FunctionActivity.this, BokeActivity2.class);
                startActivity(intent);
            } else if (v == v_my) {
                Intent intent = new Intent(FunctionActivity.this, MyActivity.class);
                startActivity(intent);
            }
        }
    };

    //
    private void initview() {
        v_gongqing = findViewById(R.id.id_v_gongqing);
        v_gongqing.setOnClickListener(itemClick);
        v_control = findViewById(R.id.id_gate_control);
        v_control.setOnClickListener(itemClick);
        v_water = findViewById(R.id.id_v_water);
        v_water.setOnClickListener(itemClick);
//        v_peishui = findViewById(R.id.id_v_peishui);
//        v_peishui.setOnClickListener(itemClick);
        v_adcp = findViewById(R.id.id_v_adcp);
        v_adcp.setOnClickListener(itemClick);
        v_gis = findViewById(R.id.id_v_gis);
        v_gis.setOnClickListener(itemClick);
        v_main = findViewById(R.id.id_bottom_main);
        v_main.setOnClickListener(itemClick);
        v_chat = findViewById(R.id.id_bottom_chat);
        v_chat.setOnClickListener(itemClick);
        v_bbs = findViewById(R.id.id_bottom_bbs);
        v_bbs.setOnClickListener(itemClick);
        v_my = findViewById(R.id.id_bottom_my);
        v_my.setOnClickListener(itemClick);

    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        closeDialog();
    }


    // 升级线程
    private class UpgradThread extends Thread {

        String path;

        public void setPath(String path) {
            this.path = path;
        }

        @Override
        public void run() {

            InputStream in = null;
            OutputStream fileOutputStream = null;

            try {
                // 创建一个url对象
                URL url = new URL(path);
                // 通過url对象，创建一个HttpURLConnection对象（连接）
                HttpURLConnection urlConnection = (HttpURLConnection) url
                        .openConnection();
                // 通过HttpURLConnection对象，得到InputStream
                in =  urlConnection.getInputStream();
                fileOutputStream = new FileOutputStream(new File("/sdcard/xkh.apk"));
                long sum = 0;
                int num;
                byte[] buffer = new byte[1024];
                while((num = in.read(buffer))!= -1)
                {
                    fileOutputStream.write(buffer,0,num);
                    fileOutputStream.flush();
                    sum += num;
                    final long tmpsum = sum;
                    UIHandler.uiHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            progressDialog.setProgress((int)(tmpsum*100.0/(15*1024*1024)));
                        }
                    });

                }

                UIHandler.uiHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        progressDialog.dismiss();
                        update();
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try {
                    if (in != null) {
                        in.close();
                    }

                    if (fileOutputStream != null)
                    {
                        fileOutputStream.close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 解包升级
    void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(Environment
                        .getExternalStorageDirectory(), "xkh.apk")),
                "application/vnd.android.package-archive");
        startActivity(intent);
    }
}
